package com.android.fastride.view.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.TextureMapView;
import com.android.fastride.map.overlay.WalkRouteOverlay;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.android.fastride.Constant;
import com.android.fastride.R;
import com.android.fastride.contract.OrderDetailContract;
import com.android.fastride.map.util.AMapUtil;
import com.android.fastride.map.util.ToastUtil;
import com.android.fastride.model.db.entity.Order;
import com.android.fastride.present.OrderDetailPresent;
import com.android.fastride.view.widget.MapContainer;
import com.android.fastride.view.widget.TopBar;
import com.peng.library.mantis.expand.data.MantisDataFragment;
import com.peng.library.mantis.hint.HintConfig;
import com.peng.library.mantis.mvp.BindPresent;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

@BindPresent(OrderDetailPresent.class)
public class OrderDetailFragment extends MantisDataFragment<OrderDetailContract.PRESENT, Order>
        implements OrderDetailContract.VIEW, Constant, RouteSearch.OnRouteSearchListener, com
        .amap.api.maps.AMap.OnMapLoadedListener {

    private RouteSearch mRouteSearch;
    private WalkRouteResult mWalkRouteResult;
    private LatLonPoint mStartPoint = new LatLonPoint(39.996678, 116.479271);//起点，39.996678,
    // 116.479271
    private LatLonPoint mEndPoint = new LatLonPoint(39.997796, 116.468939);//终点，39.997796,116.468939
    private final int ROUTE_TYPE_WALK = 3;

    private WalkRouteOverlay walkRouteOverlay;

    View view;
    Unbinder unbinder;
    @BindView(R.id.tb_top_bar)
    TopBar tbTopBar;
    @BindView(R.id.cl_new_order)
    ConstraintLayout clNewOrder;
    @BindView(R.id.cl_pick_up)
    ConstraintLayout clPickUp;
    @BindView(R.id.cl_completed)
    ConstraintLayout clCompleted;
    @BindView(R.id.mc_gaode)
    MapContainer mcGaode;
    @BindView(R.id.route_map)
    TextureMapView routeMap;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;

    public AMap aMap;

    private int mOrderStatus;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mOrderStatus = bundle.getInt(ORDER_STATUS, ORDER_COMPLETED);
        }
    }

    public void setBundle(Bundle bundle) {
        this.setArguments(bundle);
    }

    /**
     * 使用new 关键字生成时用
     *
     * @param type
     * @return
     */
    public static OrderDetailFragment newInstance(int type) {
        OrderDetailFragment instance = new OrderDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(Constant.ORDER_STATUS, type);
        instance.setArguments(bundle);
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
            Bundle savedInstanceState, HintConfig.Builder hintConfigBuilder) {
        view = inflater.inflate(R.layout.fragment_delivery_order_details, container, false);
        ButterKnife.bind(this, view);
        tbTopBar.setOnLeftAndRightClickListener(new TopBar.OnLeftAndRightClickListener() {
            @Override
            public void OnLeftButtonClick() {
                getActivity().finish();
            }

            @Override
            public void OnRightButtonClick() {

            }
        });
        initView();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        aMap = routeMap.getMap();
        aMap.setOnMapLoadedListener(this);
        routeMap.onCreate(savedInstanceState);
        mRouteSearch = new RouteSearch(getContext());
        mRouteSearch.setRouteSearchListener(this);
    }

    private void initView() {
        mcGaode.setScrollView(scrollView);
        if (mOrderStatus == ORDER_DISPATCH | mOrderStatus == ORDER_PICK_UP) {
            // 派送中
            clNewOrder.setVisibility(View.GONE);
            clCompleted.setVisibility(View.GONE);
            clPickUp.setVisibility(View.VISIBLE);
        } else if (mOrderStatus == ORDER_COMPLETED) {
            // 已完成
            clNewOrder.setVisibility(View.GONE);
            clCompleted.setVisibility(View.VISIBLE);
            clPickUp.setVisibility(View.GONE);
        } else if (mOrderStatus == ORDER_PENDING) {
            // 新订单
            clNewOrder.setVisibility(View.VISIBLE);
            clCompleted.setVisibility(View.GONE);
            clPickUp.setVisibility(View.GONE);
        } else {
            clNewOrder.setVisibility(View.GONE);
            clCompleted.setVisibility(View.GONE);
            clPickUp.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    @Override
    public void onReceiveData(Order order) {

    }

    @Override
    public void onReceiveError(Throwable error) {

    }

    @Override
    public void onResume() {
        super.onResume();
        routeMap.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        routeMap.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        routeMap.onDestroy();
    }

    /**
     * 开始搜索路径规划方案
     */
    public void searchRouteResult(int routeType) {
        if (mStartPoint == null) {
            ToastUtil.show(getContext(), "定位中，稍后再试...");
            return;
        }
        if (mEndPoint == null) {
            ToastUtil.show(getContext(), "终点未设置");
        }
//        showProgressDialog();
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                mStartPoint, mEndPoint);
        if (routeType == ROUTE_TYPE_WALK) {// 步行路径规划
            RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(fromAndTo);
            mRouteSearch.calculateWalkRouteAsyn(query);// 异步路径规划步行模式查询
        }
    }

    @Override
    public void onMapLoaded() {
        searchRouteResult(ROUTE_TYPE_WALK);
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {

    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {
        aMap.clear();// 清理地图上的所有覆盖物
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mWalkRouteResult = result;
                    final WalkPath walkPath = mWalkRouteResult.getPaths()
                            .get(0);
                    if (walkRouteOverlay != null) {
                        walkRouteOverlay.removeFromMap();
                    }
                    WalkRouteOverlay
                            walkRouteOverlay = new WalkRouteOverlay(
                            getContext(), aMap, walkPath,
                            mWalkRouteResult.getStartPos(),
                            mWalkRouteResult.getTargetPos());
                    walkRouteOverlay.addToMap();
                    walkRouteOverlay.zoomToSpan();
                    int dis = (int) walkPath.getDistance();
                    int dur = (int) walkPath.getDuration();
                    String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength
                            (dis) + ")";
                    /*mRotueTimeDes.setText(des);
                    mRouteDetailDes.setVisibility(View.GONE);
                    mBottomLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(mContext,
                                    WalkRouteDetailActivity.class);
                            intent.putExtra("walk_path", walkPath);
                            intent.putExtra("walk_result",
                                    mWalkRouteResult);
                            startActivity(intent);
                        }
                    });*/
                } else if (result != null && result.getPaths() == null) {
//                    ToastUtil.show(mContext, R.string.no_result);
                }
            } else {
//                ToastUtil.show(mContext, R.string.no_result);
            }
        } else {
//            ToastUtil.showerror(this.getApplicationContext(), errorCode);
        }
    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }
}
